package com.chs.recoginition.core.config;

import com.chs.recoginition.core.handler.ForbiddenHandler;
import com.chs.recoginition.core.handler.UnauthorizedHandler;
import com.chs.recoginition.service.IUserinfoService;
import com.chs.recoginition.service.impl.UserinfoServiceImpl;
import com.chs.recoginition.core.utils.SpringContextUtils;
import com.chs.recoginition.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.Arrays;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private WebConfig webConfig;

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder, IUserinfoService authorityService) throws Exception {
        authenticationManagerBuilder
                // 设置UserDetailsService
                .userDetailsService(authorityService)
                // 使用BCrypt进行密码的hash
                .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(SpringContextUtils.getBean(IUserinfoService.class));
    }
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        String password = passwordEncoder.encode("123");
//        auth.inMemoryAuthentication().withUser("admin").password(password).roles("admin");
//    }
    /**
     * 环境中没有 AuthorityService 实例才创建默认实现
     */
    @Bean
    @ConditionalOnMissingBean(IUserinfoService.class)
    public IUserinfoService authorityService() {
        return new UserinfoServiceImpl();
    }

    /**
     * 装载BCrypt密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }



    // @formatter:off
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        System.out.println(Arrays.toString(webConfig.getUnlicensedUrls()));
        httpSecurity
                // 由于使用的是JWT，我们这里不需要csrf
                .csrf().disable()
                // 基于token，所以不需要session
     //           .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                    // 允许无授权访问静态文件
                    .antMatchers(HttpMethod.GET, webConfig.getStaticUrls()).permitAll()
                    // 允许无授权访问的API
                    .antMatchers(webConfig.getUnlicensedUrls()).permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .logout()
//                    .logoutUrl("/api/auth/loginout")
                    .invalidateHttpSession(true)
                    .and()
                // 被拦截时的处理
                .exceptionHandling()
                    // 未登录处理
                    .authenticationEntryPoint(unauthorizedHandler())
                    // 访问受限处理
                    .accessDeniedHandler(forbiddenHandler());

        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 防止iframe
        httpSecurity.headers().frameOptions().disable();
    }
    // @formatter:on

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public AuthenticationEntryPoint unauthorizedHandler() {
        return new UnauthorizedHandler();
    }

    @Bean
    public AccessDeniedHandler forbiddenHandler() {
        return new ForbiddenHandler();
    }
}